#include <reg52.h>
#include "intrins.h"
#include <stdio.h> //用于printf
#define uchar unsigned char
#define AT24C02_ADDR 0xa0
sbit SDA = P2 ^ 0;
sbit SCL = P2 ^ 1;
void delay() //短暂5us延时
{
	;
	;
}
void IIC_Start(void)
{
	SDA = 1;
	SCL = 1;
	delay();
	SDA = 0;
	delay();
	// SCL = 0;
}
void IIC_End(void)
{
	SDA = 0;
	SCL = 1;
	delay();
	SDA = 1;
	delay();
}
void IIC_Ack()
{
	uchar i = 0;
	SCL = 1;
	delay();
	while (SDA == 1 && i < 250)
		i++;
	SCL = 0; //SCL=0，SDA可以改变
	delay();
}
void write_byte(uchar dat)
{
	uchar i;
	for (i = 0; i < 8; i++)
	{
		dat = dat << 1; //如1011 0011 左移一位为0110 0110

		SCL = 0; //SDL=0，才能往SDA送数据，或从SDA读数据
		delay();
		SDA = CY; //上面左移后进位为1
		delay();
		SCL = 1;
		delay();
	}
	SCL = 0;
	//      delay();
	SDA = 1; //释放SDA
	delay();
}
uchar read_byte()
{
	uchar dat = 0, tmp, i;
	SCL = 0;
	delay();
	for (i = 0; i < 8; i++)
	{
		SCL = 1; //让SDA保持稳定，准备读取
		delay();
		tmp = SDA; //读取此时SDA的状态
		dat = dat << 1;
		dat = dat | tmp;
		delay();
		SCL = 0; //释放SDA总线，为下一次读取做准备
		delay();
	}
	return dat;
}
void write_AT24C02(uchar unit_addr, uchar dat)
{
	IIC_Start();
	write_byte(AT24C02_ADDR + 0); //下一个字节为写，所以是+0
	IIC_Ack();
	write_byte(unit_addr);
	IIC_Ack();
	write_byte(dat);
	IIC_Ack();
	IIC_End();
}
uchar read_AT24C02(uchar unit_addr)
{
	uchar dat;
	/*先写数据*/
	IIC_Start();
	write_byte(AT24C02_ADDR + 0); //下一个字节为写
	IIC_Ack();
	write_byte(unit_addr);
	IIC_Ack();
	IIC_Start();
	write_byte(AT24C02_ADDR + 1); //下一个字节为读
	IIC_Ack();
	dat = read_byte();
	IIC_End();
	return dat;
}
void IIC_Init()
{
	SDA = 1;
	delay();
	SCL = 1;
	delay();
}

void Delay10ms() //@11.0592MHz
{
	unsigned char i, j;
	i = 18;
	j = 235;
	do
	{
		while (--j)
			;
	} while (--i);
}
void InitUART(void)
{

	SCON = 0x50;  // SCON: 模式 1, 8-bit UART, 使能接收
	TMOD |= 0x20; // TMOD: timer 1, mode 2, 8-bit 重装
	TH1 = 0xFD;	  // TH1:  重装值 9600 波特率 晶振 11.0592MHz
	TR1 = 1;	  // TR1:  timer 1 打开
	EA = 1;		  //打开总中断
				  // ES    = 1;                  //打开串口中断
}
void main(void)
{
	InitUART();
	write_AT24C02(211, 0xae);
	Delay10ms(); //写完后,必须延时一定的时间才可以读取,否则不行
	P0 = read_AT24C02(211);
	printf("%bu\n", P0);
	while (1)
		;
}
